package netWork;

import javafx.concurrent.Service;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class newTcpEchoServer {
    /**
     * 服务器端
     */
    Socket socket = null;
    ServerSocket serverSocket = null;
    public newTcpEchoServer() throws IOException {
        serverSocket = new ServerSocket(9999);
    }
    public void start() throws IOException {
        System.out.println("服务器启动");
        ExecutorService service = Executors.newFixedThreadPool(10);
        while (true){
            socket = serverSocket.accept();
                service.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            processConnection(socket);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
        }
    }
    private void processConnection(Socket clientSocket) throws IOException {
            //阻塞获取请求
            try (InputStream inputStream = clientSocket.getInputStream();
                 OutputStream outputStream = clientSocket.getOutputStream();
                 Scanner scannerInput = new Scanner(inputStream);
                 PrintWriter printWriter = new PrintWriter(outputStream);){
                while (true){
                    if(!scannerInput.hasNext()){
                        System.out.printf("客户端下线 [%s : %d ]\n",clientSocket.getInetAddress().toString(),clientSocket.getPort());
                        break;
                    }
                    String request = scannerInput.next();
                //处理发来的请求
                String response = process(request);
                //返回发送来的请求
                printWriter.println(response);
                //清空缓存
                printWriter.flush();
                System.out.printf("[%s : %d]  req: %s resp %s\n",
                        clientSocket.getInetAddress().getHostAddress(),clientSocket.getPort(),request,response);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                //释放连接
                clientSocket.close();

            }



    }

    private String process(String request) {
        return request+"你好";
    }

    public static void main(String[] args) throws IOException {
        newTcpEchoServer newTcpEchoServer = new newTcpEchoServer();
        newTcpEchoServer.start();
    }
}
